<template>


  <div class="order-detail-container">
    <div class="order-card">
      <!-- 订单状态展示 -->
      <div class="order-status">
        <el-steps :active="statusStep" align-center>
          <el-step title="创建订单" :description="formatDate(order.order_time)" />
          <el-step title="审核订单" :description="order.order_status === '未审核' ? '待审核' : '已审核'" />
          <el-step title="支付订单" :description="order.order_status === '已审核,未支付' ? '待支付' : '已支付'" />
          <el-step title="完成交易" :description="order.order_status === '已生效' ? '已完成' : '等待完成'" />
        </el-steps>

        <div class="status-tag-container">
          <el-tag :type="statusTagType(order.order_status)" size="large">
            {{ order.order_status }}
          </el-tag>
        </div>
      </div>

      <!-- 订单基本信息 -->
      <div class="order-info">
        <div class="info-row">
          <span class="label">订单号：</span>
          <span class="value">{{ order.order_id }}</span>
          <el-button type="info" size="small" plain @click="copyOrderId">复制</el-button>
        </div>
        <div class="info-row">
          <span class="label">下单时间：</span>
          <span class="value">{{ formatDate(order.order_time) }}</span>
        </div>
        <div class="info-row">
          <span class="label">订单状态：</span>
          <span class="value">
            <el-tag :type="statusTagType(order.order_status)" size="small">
              {{ order.order_status }}
            </el-tag>
          </span>
        </div>
      </div>

      <!-- 商品信息 -->
      <div class="product-info">
        <h3>商品信息</h3>
        <div class="product-card">
          <div class="product-image">
            <el-image :src="order.order_product.image || 'https://shadow.elemecdn.com/app/element/hamburger.9cf7b091-55e9-11e9-a976-7f4d0b07eef6.png'">
              <template #error>
                <div class="image-error">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </div>
          <div class="product-details">
            <h4>{{ order.order_product.name }}</h4>
            <p class="product-desc">{{ order.order_product.description || '暂无商品描述' }}</p>
            <div class="price-info">
              <span class="price">￥{{ order.order_price }}</span>
              <span class="original-price" v-if="order.order_product.original_price">
                ￥{{ order.order_product.original_price }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 支付信息 -->
      <div class="payment-info">
        <h3>支付信息</h3>
        <div class="info-card">
          <div class="info-row">
            <span class="label">商品金额：</span>
            <span class="value">￥{{ order.order_price }}</span>
          </div>
          <div class="info-row">
            <span class="label">优惠金额：</span>
            <span class="value">-￥0.00</span>
          </div>
          <div class="info-row total">
            <span class="label">实付金额：</span>
            <span class="value total-price">￥{{ order.order_price }}</span>
          </div>
        </div>
      </div>

      <!-- 操作区域 -->
      <div class="action-area">
        <el-button 
          type="primary" 
          v-if="order.order_status === '已审核,未支付'" 
          @click="payOrder"
        >
          立即支付
        </el-button>
        <el-button 
          type="primary" 
          v-if="order.order_status === '未审核'" 
          @click="goToReview"
        >
          进入审核
        </el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>

    <!-- 支付加载动画 -->
    <el-dialog v-model="paying" title="支付处理中" width="30%" :show-close="false" :close-on-click-modal="false" center>
      <div class="paying-container">
        <el-progress type="circle" :percentage="payProgress" :color="payProgressColor" />
        <p class="paying-text">{{ payProgressText }}</p>
        <p v-if="payError" class="error-text">{{ payError }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import axios from 'axios';

const route = useRoute();
const router = useRouter();
const order = ref({
  order_id: '',
  order_status: '',
  order_price: 0,
  order_time: '',
  order_user: { id: '', username: '' },
  order_product: {
    id: '',
    name: '',
    description: '',
    price: 0,
    original_price: 0,
    image: ''
  }
});
const paying = ref(false);
const payProgress = ref(0);
const payProgressText = ref('正在连接支付网关...');
const payProgressColor = ref('#409EFF');
const payError = ref('');
const paymentWindow = ref(null);
const checkInterval = ref(null);

// 根据订单状态计算步骤进度
const statusStep = computed(() => {
  switch(order.value.order_status) {
    case '未审核': return 1;
    case '已审核,未支付': return 2;
    case '已支付': return 3;
    case '已生效': return 4;
    default: return 1;
  }
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString().slice(0,5);
};

// 状态标签类型
const statusTagType = (status) => {
  switch(status) {
    case '未审核': return 'info';
    case '已审核,未支付': return 'warning';
    case '已支付': return 'primary';
    case '已生效': return 'success';
    default: return 'info';
  }
};

// 复制订单号
const copyOrderId = () => {
  navigator.clipboard.writeText(order.value.order_id)
    .then(() => {
      ElMessage.success('订单号已复制');
    })
    .catch(() => {
      ElMessage.error('复制失败');
    });
};

// 获取订单详情
const fetchOrderDetail = async () => {
  if (!route.params.id) {
    ElMessage.error('订单ID无效');
    return;
  }

  try {
    const response = await axios.get(`http://127.0.0.1:8000/orders/order_detail/${route.params.id}/`);

    if (response.data.status === 200) {
      order.value = response.data.data;
    } else {
      ElMessage.error('获取订单详情失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    ElMessage.error('获取订单详情失败，请稍后重试');
  }
};

// 支付订单
const payOrder = () => {
  ElMessageBox.confirm(
    `确定要支付订单 ${order.value.order_id} 吗？金额: ￥${order.value.order_price}`,
    '确认支付',
    {
      confirmButtonText: '确认支付',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    startPaymentProcess();
  }).catch(() => {
    // 用户取消
  });
};

// 进入审核
const goToReview = () => {
  router.push({
    name: 'InsuranceProcess',
    query: {
      orderId: order.value.order_id
    }
  });
};

// 开始支付流程
const startPaymentProcess = async () => {
  paying.value = true;
  payProgress.value = 0;
  payProgressText.value = '正在生成支付链接...';
  payError.value = '';

  try {
    // 1. 调用后端获取支付链接
    const response = await axios.get(
      `http://127.0.0.1:8000/orders/alipay/?order_id=${order.value.order_id}`
    );

    if (response.data.status === 200) {
      payProgress.value = 30;
      payProgressText.value = '正在打开支付页面...';

      // 2. 在新窗口打开支付链接
      paymentWindow.value = window.open(
        response.data.data.url,
        '_blank',
        'width=600,height=800'
      );

      // 3. 启动支付状态检查
      payProgress.value = 50;
      payProgressText.value = '等待支付完成...';
      startPaymentStatusCheck();
    } else {
      payError.value = response.data.msg || '获取支付链接失败';
      payProgressColor.value = '#F56C6C';
    }
  } catch (error) {
    console.error('支付失败:', error);
    payError.value = '支付服务异常，请稍后重试';
    payProgressColor.value = '#F56C6C';
  }
};

// 开始支付状态检查
const startPaymentStatusCheck = () => {
  clearInterval(checkInterval.value);

  checkInterval.value = setInterval(async () => {
    try {
      // 检查订单状态
      const statusResponse = await axios.get(
        `http://127.0.0.1:8000/orders/check-status/?order_id=${order.value.order_id}`
      );

      if (statusResponse.data.status === 200) {
        const orderStatus = statusResponse.data.data.status;

        // 支付成功
        if (orderStatus === '已生效') {
          clearInterval(checkInterval.value);
          payProgress.value = 100;
          payProgressText.value = '支付成功！';
          payProgressColor.value = '#67C23A';

          // 更新本地订单状态
          order.value.order_status = '已生效';

          // 关闭支付窗口
          if (paymentWindow.value && !paymentWindow.value.closed) {
            paymentWindow.value.close();
          }

          // 3秒后关闭对话框
          setTimeout(() => {
            paying.value = false;
            ElMessage.success('支付成功！');
          }, 3000);
        }
        // 支付失败
        else if (orderStatus === '支付失败') {
          clearInterval(checkInterval.value);
          payProgressText.value = '支付失败';
          payError.value = statusResponse.data.data.msg || '支付失败';
          payProgressColor.value = '#F56C6C';
        }
      }
    } catch (error) {
      console.error('检查支付状态失败:', error);
      payError.value = '检查支付状态失败';
    }

    // 超过5分钟自动取消
    if (payProgress.value >= 100) {
      clearInterval(checkInterval.value);
    } else {
      payProgress.value = Math.min(payProgress.value + 2, 95);
    }
  }, 3000);
};

// 返回订单列表
const goBack = () => {
  router.push('/');
};

onMounted(() => {
  fetchOrderDetail();
});

// 组件卸载时清除定时器
onBeforeUnmount(() => {
  clearInterval(checkInterval.value);
  if (paymentWindow.value && !paymentWindow.value.closed) {
    paymentWindow.value.close();
  }
});
</script>

<style scoped>
/* 保持原有样式不变 */
.order-detail-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.08);
}

.order-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  padding: 25px;
  transition: all 0.3s ease;
}

.order-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.order-status {
  margin-bottom: 30px;
  position: relative;
  padding: 15px;
  background: linear-gradient(135deg, #f8f9fc, #eef2f8);
  border-radius: 8px;
}

.status-tag-container {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

.order-info, .payment-info {
  margin-bottom: 30px;
  padding: 15px;
  background: #f9fafc;
  border-radius: 8px;
}

.info-row {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #eee;
}

.info-row.total {
  border-top: 1px solid #eee;
  border-bottom: none;
  margin-top: 10px;
  padding-top: 15px;
}

.label {
  width: 100px;
  color: #606266;
  font-weight: 600;
}

.value {
  flex: 1;
  color: #303133;
  font-size: 15px;
}

.total-price {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
}

.product-info h3, .payment-info h3 {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
  color: #303133;
  font-size: 18px;
}

.product-card {
  display: flex;
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.product-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.product-image {
  width: 180px;
  height: 180px;
  margin-right: 20px;
  border-radius: 8px;
  overflow: hidden;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.product-image .el-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  font-size: 40px;
}

.product-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-details h4 {
  font-size: 20px;
  margin-bottom: 12px;
  color: #1f2d3d;
}

.product-desc {
  color: #606266;
  margin-bottom: 15px;
  line-height: 1.6;
  flex-grow: 1;
}

.price-info {
  display: flex;
  align-items: center;
}

.price {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  font-size: 16px;
  color: #909399;
  text-decoration: line-through;
}

.info-card {
  padding: 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.action-area {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  gap: 20px;
}

.paying-container {
  text-align: center;
  padding: 20px;
}

.paying-text {
  margin-top: 20px;
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

.error-text {
  color: #F56C6C;
  margin-top: 10px;
  font-size: 14px;
  font-weight: 500;
}

@media (max-width: 768px) {
  .order-detail-container {
    padding: 10px;
  }

  .order-card {
    padding: 15px;
  }

  .product-card {
    flex-direction: column;
  }

  .product-image {
    width: 100%;
    margin-right: 0;
    margin-bottom: 15px;
  }

  .action-area {
    flex-direction: column;
    gap: 10px;
  }

  .action-area .el-button {
    width: 100%;
  }

  .status-tag-container {
    position: relative;
    top: 0;
    right: 0;
    margin-top: 15px;
    text-align: center;
  }
}
</style>